Android Development Using HttpURLConnection Network Programming Detailed Explanation [Attached Source Code Download]

  • 2021-08-12 03:38:26
  • OfStack

In this paper, an example is given to describe the development of Android and the use of HttpURLConnection for network programming. Share it for your reference, as follows:

--HttpURLConnection

URLConnection has been very convenient to exchange information with designated sites, and there is another subclass under URLConnection: HttpURLConnection, HttpURLConnection is improved on the basis of URLConnection, and a convenient method for operating HTTP resources is added.

setRequestMethod(String) Set the method for sending requests
getResponseCode() Gets the response code of the server
getResponseMessage() Getting the response message from the server

a) Code for get request:


conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);// The number of milliseconds the connection timed out 
conn.setReadTimeout(8000);// Number of milliseconds read timeout 

b) Code for post request


conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");

c) Close the connection


if(conn!=null)conn.disconnect();

To implement multithreaded downloads:

a) Creating an URL object
b) Gets the size of the resource to which the specified URL object points: getContentLength()
c) Creates an empty file on the local disk that is the same size as a network resource
d) Calculates the specified portion of network resources downloaded by each thread application
e) creates and starts multiple threads in turn to download a specified portion of the network resource

Note the permissions required:


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

For more instructions on Android permission control, please refer to Android Manifest Function and Permission Description Encyclopedia

Here I simply use HttpURLConnection under 1 to parse text and picture

The programming steps are as follows:

1. Write the layout file first:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">
 <Button
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:onClick="click"
  android:text=" Load pictures "
   />
 <ImageView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_centerInParent="true"
  android:id="@+id/iv"/>
 <Button
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:onClick="click2"
  android:text=" Load text "
   />
 <TextView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:id="@+id/tv"/>
</LinearLayout>

2. The realization of text parsing in MainActivity:


// Text parsing 
public void click2(View view){
 new Thread(){
  public void run() {
   try {
    URL url2=new URL("http://www.baidu.com");
    HttpURLConnection conn=(HttpURLConnection) url2.openConnection();
    conn.setRequestMethod("GET");
    conn.setConnectTimeout(8000);
    conn.setReadTimeout(8000);
    conn.connect();
    if(conn.getResponseCode()==200){
     InputStream inputStream=conn.getInputStream();
     ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
     byte[]b=new byte[512];
     int len;
     while ((len=inputStream.read(b))!=-1) {
      byteArrayOutputStream.write(b,0,len);
     }
     String text=new String(byteArrayOutputStream.toByteArray(),"UTF-8");
     Message msg=Message.obtain();
     msg.what=0x124;
     msg.obj=text;
     handler.sendMessage(msg);
    }
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  };
 }.start();
}

GET mode is used here ~ POST mode can also be used ~

3. The realization of picture parsing in MainActivity:


// Picture parsing 
public void click(View view){
 final File file=new File(getCacheDir(),"2.png");
 if(file.exists()){
  System.out.println(" Using cache ");
  Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
  iv.setImageBitmap(bitmap);
 }else{
  new Thread(){
   public void run() {
    try {
     URL url=new URL("http://192.168.207.1:8090/2.png");
     System.out.println(" Use the network ");
     HttpURLConnection conn=(HttpURLConnection) url.openConnection();
     conn.setRequestMethod("GET");
     conn.setConnectTimeout(8000);
     conn.setReadTimeout(8000);
     conn.connect();
     if(200==conn.getResponseCode()){
      // Normal connection 
      InputStream is=conn.getInputStream();
      //Bitmap bitmap=BitmapFactory.decodeStream(is);
      FileOutputStream fileOutputStream=new FileOutputStream(file);
      int len;
      byte[] b=new byte[1024];
      while ((len=is.read(b))!=-1) {
       fileOutputStream.write(b,0,len);
      }
      fileOutputStream.close();
      Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
      fileOutputStream.flush();
      Message msg=Message.obtain();
      msg.what=0x123;
      msg.obj=bitmap;
      handler.sendMessage(msg);
     }
    } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   };
  }.start();
 }
}

This picture analysis realizes the cache of pictures. When you want to load pictures again, you can get pictures in the cached files, which can reduce the use of memory ~

I put this picture in this directory on the server side\ apache-tomcat-7. 0.37\ webapps\ upload. You can download this picture from the server and save it in a file ~

4. Finally, load the text and pictures


private Handler handler=new Handler(){
 public void handleMessage(android.os.Message msg) {
  if(msg.what==0x123){
   Bitmap bitmap=(Bitmap) msg.obj;
   iv.setImageBitmap(bitmap);
  }
  else if(msg.what==0x124){
   String text=(String) msg.obj;
   tv.setText(text);
  }
 };
};

I won't post the renderings, just know how to write the code ~

The complete MainActivity code is as follows:


public class MainActivity extends Activity {
 private ImageView iv;
 private TextView tv;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  iv=(ImageView) findViewById(R.id.iv);
  tv=(TextView) findViewById(R.id.tv);
 }
 private Handler handler=new Handler(){
  public void handleMessage(android.os.Message msg) {
   if(msg.what==0x123){
    Bitmap bitmap=(Bitmap) msg.obj;
    iv.setImageBitmap(bitmap);
   }
   else if(msg.what==0x124){
    String text=(String) msg.obj;
    tv.setText(text);
   }
  };
 };
 // Text parsing 
 public void click2(View view){
  new Thread(){
   public void run() {
    try {
     URL url2=new URL("http://www.baidu.com");
     HttpURLConnection conn=(HttpURLConnection) url2.openConnection();
     conn.setRequestMethod("GET");
     conn.setConnectTimeout(8000);
     conn.setReadTimeout(8000);
     conn.connect();
     if(conn.getResponseCode()==200){
      InputStream inputStream=conn.getInputStream();
      ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
      byte[]b=new byte[512];
      int len;
      while ((len=inputStream.read(b))!=-1) {
       byteArrayOutputStream.write(b,0,len);
      }
      String text=new String(byteArrayOutputStream.toByteArray(),"UTF-8");
      Message msg=Message.obtain();
      msg.what=0x124;
      msg.obj=text;
      handler.sendMessage(msg);
     }
    } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   };
  }.start();
 }
 // Picture parsing 
 public void click(View view){
  final File file=new File(getCacheDir(),"2.png");
  if(file.exists()){
   System.out.println(" Using cache ");
   Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
   iv.setImageBitmap(bitmap);
  }else{
   new Thread(){
    public void run() {
     try {
      URL url=new URL("http://192.168.207.1:8090/2.png");
      System.out.println(" Use the network ");
      HttpURLConnection conn=(HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setConnectTimeout(8000);
      conn.setReadTimeout(8000);
      conn.connect();
      if(200==conn.getResponseCode()){
       // Normal connection 
       InputStream is=conn.getInputStream();
       //Bitmap bitmap=BitmapFactory.decodeStream(is);
       FileOutputStream fileOutputStream=new FileOutputStream(file);
       int len;
       byte[] b=new byte[1024];
       while ((len=is.read(b))!=-1) {
        fileOutputStream.write(b,0,len);
       }
       fileOutputStream.close();
       Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
       fileOutputStream.flush();
       Message msg=Message.obtain();
       msg.what=0x123;
       msg.obj=bitmap;
       handler.sendMessage(msg);
      }
     } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    };
   }.start();
  }
 }
}

Attachment: Click here to download the complete example code.

More readers interested in Android can check the topics of this site: "Summary of Android Communication Mode", "Introduction and Advanced Tutorial of Android Development", "Summary of Android Debugging Skills and Common Problem Solutions", "Summary of Android Multimedia Operation Skills (Audio, Video, Recording, etc.)", "Summary of Android Basic Component Usage", "Android View View Skill Summary", "Android Layout layout Skill Summary" and "Android Control Usage Summary"

I hope this article is helpful to everyone's Android programming.


Related articles: